package com.example.questionnaire.service.impl;

import com.example.questionnaire.constant.ExpenseConstants;
import com.example.questionnaire.constant.QuestionnaireConstant;
import com.example.questionnaire.entity.PieEntity;
import com.example.questionnaire.entity.QuestionnaireEntity;
import com.example.questionnaire.service.PieService;
import com.example.questionnaire.service.QuestionnaireService;
import com.example.questionnaire.service.UserService;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.questionnaire.dao.ResultDao;
import com.example.questionnaire.entity.ResultEntity;
import com.example.questionnaire.service.ResultService;


@Service("resultService")
public class ResultServiceImpl extends ServiceImpl<ResultDao, ResultEntity> implements ResultService {
    @Autowired
    private ResultDao resultDao;
    @Autowired
    private PieService pieService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ResultEntity> page = this.page(
                new Query<ResultEntity>().getPage(params),
                new QueryWrapper<ResultEntity>()
        );


        return new PageUtils(page);
    }

    @Override
    public int collectResult(ResultEntity resultEntity) {
        int questionnaireId=resultEntity.getQuestionnaireId();
        int answererId=resultEntity.getAnswererId();
        int result=resultDao.queryIfCanAnswer(questionnaireId,answererId);
        if(result!=0) {
             resultDao.insert(resultEntity);
             return 0;
             //表示可以收集答卷结果
        }else{
            return 1;
            //表示答卷人身份不符合要求
        }
    }

    @Override
    public int queryIfCanAnswer(int questionnaire_id, int answerer_id) {
       return resultDao.queryIfCanAnswer(questionnaire_id,answerer_id);
    }


//    提交的时候limit_number-1,还差一个计费的功能 TODO 答卷计费
    @Override
    public boolean submit(ResultEntity resultEntity) {
        Integer questionnaireId = resultEntity.getQuestionnaireId();
        QuestionnaireEntity byId = questionnaireService.getById(questionnaireId);
        if (byId.getLimitNumber() == 0) {
            return false;
        }
        userService.expenseUtoT(byId.getUserId(), ExpenseConstants.releaseQuestionnaire.getStatenum());
        byId.setLimitNumber(byId.getLimitNumber() - 1);
        questionnaireService.updateById(byId);

        resultEntity.setIsFinish(1);
        resultEntity.setEndTime(new Date());
        this.updateById(resultEntity);

        //下面代码是和数据分析相关的
        String commitAnswer = resultEntity.getCommitAnswer();
        //如果是跳转题目的情况则删除"[]"字符串
        commitAnswer= commitAnswer.replace("[],", "");
        //判断有几个多选题
        int count=-1;
        for(int i=0;i<commitAnswer.length();i++){
            if(commitAnswer.charAt(i)=='['){
                count++;
            }
        }
        if(count==0) {
            //如果是没有多选题的情况将问卷所选择不同题目的答案用“,”进行分割
            String[] commit = commitAnswer.split(",");
            String answerList = resultEntity.getAnswerList();
            int[] types = new int[commit.length];
            int index = 0;
            String answerList1 = answerList.substring(0, answerList.length() - 2);
            String[] answerListSplit = answerList1.split("}");
            int jumpTotal=0;
            int temp=0;
            for(int i=0;i<answerListSplit.length;i++){
                if(!answerListSplit[i].contains("\"afterIndex\":[\"\"]")){
                    jumpTotal++;
                    temp=i;
                }
            }
            if(jumpTotal>1||temp!=0){
                return true;
            }
            //设置跳转只能是在第一题设定
            String answerListFirst=answerListSplit[0];
            String jump=null;
            if(!answerListFirst.contains("\"afterIndex\":[\"\"]")){
                jump=answerListFirst.substring(answerListFirst.indexOf("\"afterIndex\":[\"")+15,answerListFirst.indexOf("\"afterIndex\":[\"")+16);
                int jumpTo=Integer.parseInt(jump);
                int jumpToIndex=StringUtils.ordinalIndexOf(answerList1,"{\"",jumpTo);
//                jumpToIndex=jumpToIndex+2;
                int jumpIndex=StringUtils.ordinalIndexOf(answerList1,"},",1);
                jumpIndex=jumpIndex+2;
                String firstPart=answerList1.substring(0,jumpIndex);
                String SecondPart=answerList1.substring(jumpToIndex,answerList1.length());
                String real=firstPart+SecondPart;
                System.out.println(real);
                answerListSplit=real.split("}");
            }
            String startStr = "\"type\":";
            //获取问卷中每道题的题型
            for (int i = 0; i < answerListSplit.length; i++) {
                String type = answerListSplit[i].substring(answerListSplit[i].indexOf(startStr) + 7, answerListSplit[i].indexOf(startStr) + 8);
                int type1 = Integer.parseInt(type);
                types[i] = type1;
            }
            for (int i = 0; i < commit.length; i++) {
                //如果题目为单选题
                if (types[i] == 1) {
                    PieEntity pie = pieService.queryPieData(questionnaireId, i + 1);
                    //(i+1)代表题号
                    String choice = commit[i].substring(1, commit[i].length() - 1);
                    if (i == 0) {
                        choice = commit[i].substring(2, commit[i].length() - 1);
                    } else if (i == commit.length - 1) {
                        choice = commit[i].substring(1, commit[i].length() - 2);
                    }
                    PieEntity pieEntity = new PieEntity();
                    pieEntity.setProblemId(i + 1);
                    pieEntity.setOption1(choice);
                    pieEntity.setNumber1(1);
                    pieEntity.setQuestionnaireId(questionnaireId);
                    if (pie == null) {
                        pieService.addPieData(pieEntity);
                    } else {
                         if (pie.getOption1()!=null&&pie.getOption1().equals(choice)) {
                            PieEntity pieEntity2 = new PieEntity();
                            pieEntity2.setNumber1(pie.getNumber1() + 1);
                            pieEntity2.setProblemId(i + 1);
                            pieEntity2.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity2);
                        } else if (pie.getOption2()!=null&&pie.getOption2().equals(choice)) {
                            PieEntity pieEntity3 = new PieEntity();
                            pieEntity3.setNumber2(pie.getNumber2() + 1);
                            pieEntity3.setProblemId(i + 1);
                            pieEntity3.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity3);
                        } else if (pie.getOption3()!=null&&pie.getOption3().equals(choice)) {
                            PieEntity pieEntity4 = new PieEntity();
                            pieEntity4.setNumber3(pie.getNumber3() + 1);
                            pieEntity4.setProblemId(i + 1);
                            pieEntity4.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity4);
                        } else if (pie.getOption4()!=null&&pie.getOption4().equals(choice)) {
                            PieEntity pieEntity5 = new PieEntity();
                            pieEntity5.setNumber4(pie.getNumber4() + 1);
                            pieEntity5.setProblemId(i + 1);
                            pieEntity5.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity5);
                        }
                        else if (pie.getOption2() == null) {
                            PieEntity pieEntity1 = new PieEntity();
                            pieEntity1.setProblemId(i + 1);
                            pieEntity1.setOption2(choice);
                            pieEntity1.setNumber2(1);
                            pieEntity1.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity1);
                        } else if (pie.getOption3() == null) {
                            PieEntity pieEntity6 = new PieEntity();
                            pieEntity6.setProblemId(i + 1);
                            pieEntity6.setOption3(choice);
                            pieEntity6.setNumber3(1);
                            pieEntity6.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity6);
                        } else if (pie.getOption4() == null) {
                            PieEntity pieEntity7 = new PieEntity();
                            pieEntity7.setProblemId(i + 1);
                            pieEntity7.setOption4(choice);
                            pieEntity7.setNumber4(1);
                            pieEntity7.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity7);
                        }
                    }
                }
                //如果题目为填空题
                else if (types[i] == 3) {
                    PieEntity pie = pieService.queryPieData(questionnaireId, i + 1);
                    //(i+1)代表题号
                    String choice = commit[i].substring(1, commit[i].length() - 1);
                    if (i == 0) {
                        choice = commit[i].substring(2, commit[i].length() - 1);
                    }if (i == commit.length - 1) {
                        choice = commit[i].substring(1, commit[i].length() - 2);
                        if(commit.length==1){
                            choice = commit[i].substring(2, commit[i].length() - 2);
                        }
                    }
                    PieEntity pieEntity = new PieEntity();
                    pieEntity.setProblemId(i + 1);
                    pieEntity.setOption1(choice);
                    pieEntity.setNumber1(1);
                    pieEntity.setQuestionnaireId(questionnaireId);
                    if (pie == null) {
                        pieService.addPieData(pieEntity);
                    } else {
                        PieEntity pieEntity1 = new PieEntity();
                        pieEntity1.setProblemId(i + 1);
                        String before = pie.getOption1();
                        before = before + "&" + choice;
                        pieEntity1.setOption1(before);
                        pieEntity1.setNumber1(pie.getNumber1() + 1);
                        pieEntity1.setQuestionnaireId(questionnaireId);
                        pieService.updatePieData(pieEntity1);
                    }
                }
            }
        }
        //如果存在答了多选题的情况(只能多选题是第一道才能记录)
        else if(count==1&&commitAnswer.indexOf("[[")==0){
            //这里的条件是1个多选题并且必须是第一题
            String commitAnswer1=commitAnswer.substring(1,commitAnswer.length()-1);
            //把多选题的字符串提取出来
            String duoxuanCommit=commitAnswer1.substring(0, commitAnswer1.lastIndexOf("]")+1);
            //把剩余的字符串提取出来
            String remainCommit=commitAnswer1.substring(commitAnswer1.lastIndexOf("]")+2,commitAnswer1.length());
            //此多选题必须是第一题
            String[]duoxuan=duoxuanCommit.split(",");
            PieEntity pieEntitySpecial = new PieEntity();
            pieEntitySpecial.setProblemId(1);
            pieEntitySpecial.setQuestionnaireId(questionnaireId);
            PieEntity pieDuoxuan = pieService.queryPieData(questionnaireId, 1);
            boolean flag=false;//默认此题目在pie表中已经有统计数据
            for(int i=0;i<duoxuan.length;i++){
                String choice = duoxuan[i].substring(1, duoxuan[i].length() - 1);
                if (i == 0) {
                    choice = duoxuan[i].substring(2, duoxuan[i].length() - 1);
                } else if (i == duoxuan.length - 1) {
                    choice = duoxuan[i].substring(1, duoxuan[i].length() - 2);
                }
                if(duoxuan.length==1){
                    choice=duoxuan[i].substring(2, duoxuan[i].length() - 2);
                }
                 if (pieDuoxuan!=null&&null!=pieDuoxuan.getOption1()&&pieDuoxuan.getOption1().equals(choice)) {
                    pieEntitySpecial.setOption1(choice);
                    pieEntitySpecial.setNumber1(pieDuoxuan.getNumber1()+1);
                }else if (pieDuoxuan!=null&&null!=pieDuoxuan.getOption2()&&pieDuoxuan.getOption2().equals(choice)) {
                    pieEntitySpecial.setOption2(choice);
                    pieEntitySpecial.setNumber2(pieDuoxuan.getNumber2()+1);
                }else if (pieDuoxuan!=null&&null!=pieDuoxuan.getOption3()&&pieDuoxuan.getOption3().equals(choice)) {
                    pieEntitySpecial.setOption3(choice);
                    pieEntitySpecial.setNumber3(pieDuoxuan.getNumber3()+1);
                }else if (pieDuoxuan!=null&&null!=pieDuoxuan.getOption4()&&pieDuoxuan.getOption4().equals(choice)) {
                    pieEntitySpecial.setOption4(choice);
                    pieEntitySpecial.setNumber4(pieDuoxuan.getNumber4()+1);
                }
                //选项1为空说明还没有插入过此题目到数据库
                else if(pieDuoxuan==null&&flag==false) {
                    flag=true;//说明第一次答此题，插入数据，flag为false则为更新题目答题情况
                    pieEntitySpecial.setOption1(choice);
                    pieEntitySpecial.setNumber1(1);
                }else if(pieEntitySpecial.getOption2()==null&&flag==true){
                    pieEntitySpecial.setOption2(choice);
                    pieEntitySpecial.setNumber2(1);
                }else if(pieEntitySpecial.getOption3()==null&&flag==true){
                    pieEntitySpecial.setOption3(choice);
                    pieEntitySpecial.setNumber3(1);
                }else if(pieEntitySpecial.getOption4()==null&&flag==true){
                    pieEntitySpecial.setOption4(choice);
                    pieEntitySpecial.setNumber4(1);
                }
//                pieEntity.setNumber1();
            }
            if(flag==true){
                pieService.addPieData(pieEntitySpecial);
            }else{
                pieService.updatePieData(pieEntitySpecial);
            }
            //将remain字符串中所选择不同题目的答案用“,”进行分割,对remain字符串进行处理
            String[] commit = remainCommit.split(",");
            String answerList = resultEntity.getAnswerList();
            int[] types = new int[commit.length];
//            if(!remainCommit.contains(",")) {
//                types=new int[1];
//            }
            int index = 0;
            String answerList1 = answerList.substring(answerList.indexOf("}")+2, answerList.length() - 2);
            String[] answerListSplit = answerList1.split("}");
            System.out.println(answerListSplit[0]);
            String startStr = "\"type\":";
            //获取问卷中每道题的题型
            for (int i = 0; i < answerListSplit.length; i++) {
                String type = answerListSplit[i].substring(answerListSplit[i].indexOf(startStr) + 7, answerListSplit[i].indexOf(startStr) + 8);
                int type1 = Integer.parseInt(type);
                types[i] = type1;
            }
            for (int i = 0; i < commit.length; i++) {
                //如果题目为单选题
                if (types[i] == 1) {
                    PieEntity pie1 = pieService.queryPieData(questionnaireId, i + 2);
                    //(i+1)代表题号
                    String choice = commit[i].substring(0, commit[i].length() - 1);
                    if (i == 0) {
                        choice = commit[i].substring(1, commit[i].length() - 1);
                    } else if (i == commit.length - 1) {
                        choice = commit[i].substring(1, commit[i].length() -1);
                    }
                    PieEntity pieEntity = new PieEntity();
                    pieEntity.setProblemId(i + 2);
                    pieEntity.setOption1(choice);
                    pieEntity.setNumber1(1);
                    pieEntity.setQuestionnaireId(questionnaireId);
                    if (pie1 == null) {
                        pieService.addPieData(pieEntity);
                    } else {
                        if (null!=pie1.getOption1()&&pie1.getOption1().equals(choice)) {
                            PieEntity pieEntity2 = new PieEntity();
                            pieEntity2.setNumber1(pie1.getNumber1() + 1);
                            pieEntity2.setProblemId(i + 2);
                            pieEntity2.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity2);
                        } else if (null!=pie1.getOption2()&&pie1.getOption2().equals(choice)) {
                            PieEntity pieEntity3 = new PieEntity();
                            pieEntity3.setNumber2(pie1.getNumber2() + 1);
                            pieEntity3.setProblemId(i + 2);
                            pieEntity3.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity3);
                        } else if (null!=pie1.getOption3()&&pie1.getOption3().equals(choice)) {
                            PieEntity pieEntity4 = new PieEntity();
                            pieEntity4.setNumber3(pie1.getNumber3() + 1);
                            pieEntity4.setProblemId(i + 2);
                            pieEntity4.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity4);
                        } else if (null!=pie1.getOption4()&&pie1.getOption4().equals(choice)) {
                            PieEntity pieEntity5 = new PieEntity();
                            pieEntity5.setNumber4(pie1.getNumber4() + 1);
                            pieEntity5.setProblemId(i + 2);
                            pieEntity5.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity5);
                        }
                        else if (pie1.getOption2() == null) {
                            PieEntity pieEntity1 = new PieEntity();
                            pieEntity1.setProblemId(i + 2);
                            pieEntity1.setOption2(choice);
                            pieEntity1.setNumber2(1);
                            pieEntity1.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity1);
                        } else if (pie1.getOption3() == null) {
                            PieEntity pieEntity6 = new PieEntity();
                            pieEntity6.setProblemId(i + 2);
                            pieEntity6.setOption3(choice);
                            pieEntity6.setNumber3(1);
                            pieEntity6.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity6);
                        } else if (pie1.getOption4() == null) {
                            PieEntity pieEntity7 = new PieEntity();
                            pieEntity7.setProblemId(i + 2);
                            pieEntity7.setOption4(choice);
                            pieEntity7.setNumber4(1);
                            pieEntity7.setQuestionnaireId(questionnaireId);
                            pieService.updatePieData(pieEntity7);
                        }
                    }
                }
                //如果题目为填空题
                else if (types[i] == 3) {
                     PieEntity pie3 = pieService.queryPieData(questionnaireId, i + 2);
                    //(i+1)代表题号
                    String choice = commit[i].substring(1, commit[i].length() - 1);
                    if (i == 0) {
                        choice = commit[i].substring(1, commit[i].length() - 1);
                    } if (i == commit.length - 1) {
                        choice = commit[i].substring(1, commit[i].length() - 1);
                    }
                    PieEntity pieEntity = new PieEntity();
                    pieEntity.setProblemId(i + 2);
                    pieEntity.setOption1(choice);
                    pieEntity.setNumber1(1);
                    pieEntity.setQuestionnaireId(questionnaireId);
                    if (pie3 == null) {
                        pieService.addPieData(pieEntity);
                    } else {
                        PieEntity pieEntity1 = new PieEntity();
                        pieEntity1.setProblemId(i + 2);
                        String before = pie3.getOption1();
                        before = before + "&" + choice;
                        pieEntity1.setOption1(before);
                        pieEntity1.setNumber1(pie3.getNumber1() + 1);
                        pieEntity1.setQuestionnaireId(questionnaireId);
                        pieService.updatePieData(pieEntity1);
                    }
                }
            }
        }
            return true;
        }
    @Autowired
    UserService userService;

    @Autowired
    QuestionnaireService questionnaireService;
}